import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Form, Select, Input, message, Popconfirm, Card, Descriptions, Image } from 'antd';
import { 
  EyeOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined,
  PlusOutlined  // 添加缺失的导入
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;
const { Search } = Input;

interface Order {
  id: number;
  orderNo: string;
  customerName: string;
  customerPhone: string;
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'completed' | 'cancelled';
  paymentMethod: 'alipay' | 'wechat' | 'bank';
  createTime: string;
  products: OrderProduct[];
  shippingAddress: string;
}

interface OrderProduct {
  id: number;
  name: string;
  price: number;
  quantity: number;
  total: number;
  image?: string;
}

const OrderList: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [searchText, setSearchText] = useState('');
  const navigate = useNavigate();

  useEffect(() => {
    loadOrders();
  }, []);

  const loadOrders = async () => {
    setLoading(true);
    try {
      // 模拟 API 调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockData: Order[] = [
        {
          id: 1,
          orderNo: 'ORDER202401150001',
          customerName: '张三',
          customerPhone: '13800138000',
          totalAmount: 7999,
          status: 'paid',
          paymentMethod: 'alipay',
          createTime: '2024-01-15 10:30:00',
          shippingAddress: '北京市朝阳区某某街道123号',
          products: [
            {
              id: 1,
              name: 'iPhone 15 Pro',
              price: 7999,
              quantity: 1,
              total: 7999,
              image: 'https://via.placeholder.com/60x60?text=iPhone',
            },
          ],
        },
        {
          id: 2,
          orderNo: 'ORDER202401140001',
          customerName: '李四',
          customerPhone: '13900139000',
          totalAmount: 12999,
          status: 'shipped',
          paymentMethod: 'wechat',
          createTime: '2024-01-14 14:20:00',
          shippingAddress: '上海市浦东新区某某路456号',
          products: [
            {
              id: 2,
              name: 'MacBook Pro',
              price: 12999,
              quantity: 1,
              total: 12999,
              image: 'https://via.placeholder.com/60x60?text=Mac',
            },
          ],
        },
        {
          id: 3,
          orderNo: 'ORDER202401130001',
          customerName: '王五',
          customerPhone: '13700137000',
          totalAmount: 98,
          status: 'completed',
          paymentMethod: 'alipay',
          createTime: '2024-01-13 09:15:00',
          shippingAddress: '广州市天河区某某大道789号',
          products: [
            {
              id: 3,
              name: '咖啡杯',
              price: 49,
              quantity: 2,
              total: 98,
              image: 'https://via.placeholder.com/60x60?text=Cup',
            },
          ],
        },
      ];
      setOrders(mockData);
    } catch (error) {
      message.error('加载订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (order: Order) => {
    setSelectedOrder(order);
    setDetailVisible(true);
  };

  const handleEdit = (order: Order) => {
    navigate(`/orders/detail/${order.id}`);
  };

  const handleDelete = async (id: number) => {
    try {
      // 模拟删除
      await new Promise(resolve => setTimeout(resolve, 500));
      setOrders(orders.filter(order => order.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleStatusChange = async (id: number, status: Order['status']) => {
    try {
      const updatedOrders = orders.map(order =>
        order.id === id ? { ...order, status } : order
      );
      setOrders(updatedOrders);
      message.success('状态更新成功');
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const getStatusColor = (status: string) => {
    const colors = {
      pending: 'orange',
      paid: 'blue',
      shipped: 'purple',
      completed: 'green',
      cancelled: 'red',
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts = {
      pending: '待支付',
      paid: '已支付',
      shipped: '已发货',
      completed: '已完成',
      cancelled: '已取消',
    };
    return texts[status as keyof typeof texts] || status;
  };

  const getPaymentMethodText = (method: string) => {
    const texts = {
      alipay: '支付宝',
      wechat: '微信支付',
      bank: '银行卡',
    };
    return texts[method as keyof typeof texts] || method;
  };

  const filteredOrders = orders.filter(order =>
    order.orderNo.toLowerCase().includes(searchText.toLowerCase()) ||
    order.customerName.toLowerCase().includes(searchText.toLowerCase()) ||
    order.customerPhone.includes(searchText)
  );

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '手机号',
      dataIndex: 'customerPhone',
      key: 'customerPhone',
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount.toLocaleString()}`,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      render: (method: string) => getPaymentMethodText(method),
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Order) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Select
            size="small"
            value={record.status}
            style={{ width: 100 }}
            onChange={(value) => handleStatusChange(record.id, value)}
          >
            <Option value="pending">待支付</Option>
            <Option value="paid">已支付</Option>
            <Option value="shipped">已发货</Option>
            <Option value="completed">已完成</Option>
            <Option value="cancelled">已取消</Option>
          </Select>
          <Popconfirm
            title="确定删除这个订单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />}>
              新建订单
            </Button>
          </Space>
          <Search
            placeholder="搜索订单号、客户姓名或手机号"
            allowClear
            style={{ width: 300 }}
            onSearch={setSearchText}
          />
        </div>

        <Table
          columns={columns}
          dataSource={filteredOrders}
          rowKey="id"
          loading={loading}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={700}
      >
        {selectedOrder && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="订单号" span={2}>
                {selectedOrder.orderNo}
              </Descriptions.Item>
              <Descriptions.Item label="客户姓名">
                {selectedOrder.customerName}
              </Descriptions.Item>
              <Descriptions.Item label="手机号">
                {selectedOrder.customerPhone}
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                ¥{selectedOrder.totalAmount.toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {getPaymentMethodText(selectedOrder.paymentMethod)}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusColor(selectedOrder.status)}>
                  {getStatusText(selectedOrder.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="收货地址" span={2}>
                {selectedOrder.shippingAddress}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {selectedOrder.createTime}
              </Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 16 }}>
              <h4>商品清单</h4>
              <Table
                size="small"
                columns={[
                  { 
                    title: '商品', 
                    dataIndex: 'name', 
                    key: 'name',
                    render: (text: string, record: OrderProduct) => (
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        {record.image && (
                          <Image
                            width={40}
                            height={40}
                            src={record.image}
                            style={{ marginRight: 8, objectFit: 'cover' }}
                          />
                        )}
                        {text}
                      </div>
                    )
                  },
                  { title: '单价', dataIndex: 'price', key: 'price', render: (price) => `¥${price}` },
                  { title: '数量', dataIndex: 'quantity', key: 'quantity' },
                  { title: '小计', dataIndex: 'total', key: 'total', render: (total) => `¥${total}` },
                ]}
                dataSource={selectedOrder.products}
                rowKey="id"
                pagination={false}
              />
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrderList;